package com.ebuy.api.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ebuy.api.base.dto.BaseResp;
import com.ebuy.api.controller.sys.req.UserSearchReq;
import com.ebuy.api.controller.sys.resp.UserPageResp;
import com.ebuy.api.controller.sys.resp.UserResp;
import com.ebuy.api.domain.TbUser;
import com.ebuy.api.enums.StatusEnum;
import com.ebuy.api.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@Tag(name = "用户管理")
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @Operation(summary = "普通body请求")
    @PostMapping("page")
    public BaseResp page(@RequestBody @Valid UserSearchReq userSearchReq) {
        UserPageResp resp = new UserPageResp();
        Page<TbUser> page = new Page<>(userSearchReq.getPageNo(), userSearchReq.getPageSize());
        LambdaQueryWrapper<TbUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Objects.nonNull(userSearchReq.getStatus()),TbUser::getStatus,userSearchReq.getStatus());
        queryWrapper.like(!ObjectUtils.isEmpty(userSearchReq.getMobile()), TbUser::getMobile, userSearchReq.getMobile());
        IPage<TbUser> userIPage = userService.page(page, queryWrapper);
        resp.setPageNo(userIPage.getCurrent());
        resp.setPages(userIPage.getPages());
        resp.setPageSize(userIPage.getSize());
        resp.setTotalCount(userIPage.getTotal());
        if (!CollectionUtils.isEmpty(userIPage.getRecords())) {
            userIPage.getRecords().forEach(tbUser -> {
                UserResp userResp = new UserResp();
                BeanUtils.copyProperties(tbUser, userResp);
                userResp.setStatus_(StatusEnum.getByCode(tbUser.getStatus()).getMsg());
                userResp.setUpdateTime_(tbUser.getUpdateTime());
                resp.getData().add(userResp);
            });
        }
        return BaseResp.success(resp);
    }

}
